import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_base/utils/log/utils_log.dart';
import 'package:get/get.dart';
import 'package:flutter_base/base/controller/base_controller.dart';
import 'package:flutter_base/config/app_routes.dart';
import 'package:flutter_base/http/http_export.dart';
import 'package:flutter_base/user/app_user_manager.dart';
import 'package:flutter_base/utils/loading/loading_utils.dart';

class LoginLogic extends BaseController with GetSingleTickerProviderStateMixin {
  // 页面控制器
  late TabController tabController;

  // 登录表单控制器
  final TextEditingController emailController = TextEditingController();
  final TextEditingController passwordController = TextEditingController();

  // 注册表单控制器
  final TextEditingController registerEmailController = TextEditingController();
  final TextEditingController registerPasswordController =
      TextEditingController();
  final TextEditingController confirmPasswordController =
      TextEditingController();

  // 手机登录控制器（预留）
  final TextEditingController phoneController = TextEditingController();
  final TextEditingController codeController = TextEditingController();

  // 焦点控制器
  final FocusNode emailFocusNode = FocusNode();
  final FocusNode passwordFocusNode = FocusNode();
  final FocusNode registerEmailFocusNode = FocusNode();
  final FocusNode registerPasswordFocusNode = FocusNode();
  final FocusNode confirmPasswordFocusNode = FocusNode();

  // 错误状态管理
  bool emailHasError = false;
  bool passwordHasError = false;
  bool registerEmailHasError = false;
  bool registerPasswordHasError = false;
  bool confirmPasswordHasError = false;

  // 错误提示信息
  String emailErrorText = '';
  String passwordErrorText = '';
  String registerEmailErrorText = '';
  String registerPasswordErrorText = '';
  String confirmPasswordErrorText = '';

  bool agreementChecked = false;
  bool registerAgreementChecked = false;
  bool counting = false;
  bool obscurePassword = true;
  bool registerObscurePassword = true;
  bool obscureConfirmPassword = true;
  int seconds = 60;
  Timer? _timer;

  @override
  void onInit() {
    super.onInit();
    tabController = TabController(length: 2, vsync: this);
    tabController.addListener(() {
      update();
    });

    // 添加焦点监听
    _setupFocusListeners();

    // 添加文本变化监听
    _setupTextChangeListeners();
    if (kDebugMode) {
      emailController.text = 'chenxu.ios93@gmail.com';
      passwordController.text = 'cx123456';
    }
  }

  void _setupFocusListeners() {
    emailFocusNode.addListener(() {
      // 当失去焦点时验证
      if (!emailFocusNode.hasFocus) {
        _validateEmail(emailController.text);
      }
      update();
    });

    passwordFocusNode.addListener(() {
      // 当失去焦点时验证
      if (!passwordFocusNode.hasFocus) {
        _validatePassword(passwordController.text);
      }
      update();
    });

    registerEmailFocusNode.addListener(() {
      // 当失去焦点时验证
      if (!registerEmailFocusNode.hasFocus) {
        _validateRegisterEmail(registerEmailController.text);
      }
      update();
    });

    registerPasswordFocusNode.addListener(() {
      // 当失去焦点时验证
      if (!registerPasswordFocusNode.hasFocus) {
        _validateRegisterPassword(registerPasswordController.text);
      }
      update();
    });

    confirmPasswordFocusNode.addListener(() {
      // 当失去焦点时验证
      if (!confirmPasswordFocusNode.hasFocus) {
        _validateConfirmPassword(
            registerPasswordController.text, confirmPasswordController.text);
      }
      update();
    });
  }

  void _setupTextChangeListeners() {
    emailController.addListener(() {
      if (emailHasError) {
        _validateEmail(emailController.text);
      }
    });

    registerEmailController.addListener(() {
      if (registerEmailHasError) {
        _validateRegisterEmail(registerEmailController.text);
      }
    });

    registerPasswordController.addListener(() {
      if (confirmPasswordHasError) {
        _validateConfirmPassword(
            registerPasswordController.text, confirmPasswordController.text);
      }
    });

    confirmPasswordController.addListener(() {
      if (confirmPasswordHasError) {
        _validateConfirmPassword(
            registerPasswordController.text, confirmPasswordController.text);
      }
    });
  }

  // 新增：处理登录邮箱输入变化
  void onEmailChanged(String value) {
    if (emailHasError) {
      _validateEmail(value);
    }
  }

  // 新增：处理登录密码输入变化
  void onPasswordChanged(String value) {
    if (passwordHasError) {
      _validatePassword(value);
    }
  }

  // 新增：处理注册邮箱输入变化
  void onRegisterEmailChanged(String value) {
    if (registerEmailHasError) {
      _validateRegisterEmail(value);
    }
  }

  // 新增：处理注册密码输入变化
  void onRegisterPasswordChanged(String value) {
    if (registerPasswordHasError) {
      _validateRegisterPassword(value);
    }

    // 如果确认密码已输入，则同时验证确认密码
    if (confirmPasswordController.text.isNotEmpty) {
      _validateConfirmPassword(value, confirmPasswordController.text);
    }
  }

  // 新增：处理确认密码输入变化
  void onConfirmPasswordChanged(String value) {
    if (confirmPasswordHasError) {
      _validateConfirmPassword(registerPasswordController.text, value);
    }
  }

  // 移除所有焦点，触发键盘隐藏并验证表单
  void unfocusAndValidate() {
    clog('daslkdjaslkjd');
    // 移除当前焦点
    FocusManager.instance.primaryFocus?.unfocus();

    // 验证表单
    if (tabController.index == 0) {
      // 登录表单验证
      _validateEmail(emailController.text);
      _validatePassword(passwordController.text);
    } else {
      // 注册表单验证
      _validateRegisterEmail(registerEmailController.text);
      _validateRegisterPassword(registerPasswordController.text);
      _validateConfirmPassword(
          registerPasswordController.text, confirmPasswordController.text);
    }

    update();
  }

  @override
  void onClose() {
    emailController.dispose();
    passwordController.dispose();
    registerEmailController.dispose();
    registerPasswordController.dispose();
    confirmPasswordController.dispose();
    phoneController.dispose();
    codeController.dispose();

    emailFocusNode.dispose();
    passwordFocusNode.dispose();
    registerEmailFocusNode.dispose();
    registerPasswordFocusNode.dispose();
    confirmPasswordFocusNode.dispose();

    tabController.dispose();
    _timer?.cancel();
    super.onClose();
  }

  // 切换密码可见性
  void togglePasswordVisibility() {
    obscurePassword = !obscurePassword;
    update();
  }

  // 切换注册密码可见性
  void toggleRegisterPasswordVisibility() {
    registerObscurePassword = !registerObscurePassword;
    update();
  }

  // 切换确认密码可见性
  void toggleConfirmPasswordVisibility() {
    obscureConfirmPassword = !obscureConfirmPassword;
    update();
  }

  // 切换协议同意状态
  void toggleAgreement() {
    agreementChecked = !agreementChecked;
    update();
  }

  // 切换注册协议同意状态
  void toggleRegisterAgreement() {
    registerAgreementChecked = !registerAgreementChecked;
    update();
  }

  // 打开隐私政策
  void openPrivacyPolicy() {
    // 跳转到隐私政策页面
    // Get.toNamed(AppRoutes.privacyPolicy);
    LoadingUtils.showToast('隐私政策功能待实现');
  }

  // // 发送验证码
  // void sendVerificationCode() {
  //   String phone = phoneController.text.trim();
  //   if (phone.isEmpty) {
  //     LoadingUtils.showToast('请输入手机号');
  //     return;
  //   }
  //
  //   if (phone.length != 11) {
  //     LoadingUtils.showToast('请输入正确的手机号');
  //     return;
  //   }
  //
  //   if (counting) return;
  //
  //   // 发送验证码请求
  //   _sendCode(phone);
  //
  //   // 开始倒计时
  //   counting = true;
  //   seconds = 60;
  //   update();
  //
  //   _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
  //     seconds--;
  //     update();
  //     if (seconds <= 0) {
  //       timer.cancel();
  //       counting = false;
  //       update();
  //     }
  //   });
  // }

  // 发送验证码请求
  // Future<void> _sendCode(String phone) async {
  //   HttpResponse response = await HttpManager().post(
  //     API.sendVerificationCode,
  //     params: {'phone': phone},
  //     uiType: HttpUIType.toast,
  //   );
  //
  //   if (response.isSuccess) {
  //     LoadingUtils.showToast('验证码已发送');
  //   }
  // }

  // 验证邮箱格式
  bool _validateEmail(String email) {
    if (email.isEmpty) {
      emailHasError = true;
      emailErrorText = 'Email cannot be empty';
      update();
      return false;
    }

    if (!GetUtils.isEmail(email)) {
      emailHasError = true;
      emailErrorText = 'Invalid email format';
      update();
      return false;
    }

    emailHasError = false;
    emailErrorText = '';
    update();
    return true;
  }

  // 验证注册邮箱格式
  bool _validateRegisterEmail(String email) {
    if (email.isEmpty) {
      registerEmailHasError = true;
      registerEmailErrorText = 'Email cannot be empty';
      update();
      return false;
    }

    if (!GetUtils.isEmail(email)) {
      registerEmailHasError = true;
      registerEmailErrorText = 'Invalid email format';
      update();
      return false;
    }

    registerEmailHasError = false;
    registerEmailErrorText = '';
    update();
    return true;
  }

  // 验证密码
  bool _validatePassword(String password) {
    if (password.isEmpty) {
      passwordHasError = true;
      passwordErrorText = 'Password cannot be empty';
      update();
      return false;
    }

    if (password.length < 6) {
      passwordHasError = true;
      passwordErrorText = 'Password too short';
      update();
      return false;
    }

    passwordHasError = false;
    passwordErrorText = '';
    update();
    return true;
  }

  // 验证注册密码
  bool _validateRegisterPassword(String password) {
    if (password.isEmpty) {
      registerPasswordHasError = true;
      registerPasswordErrorText = 'Password cannot be empty';
      update();
      return false;
    }

    if (password.length < 8) {
      registerPasswordHasError = true;
      registerPasswordErrorText = 'Password too short';
      update();
      return false;
    }

    registerPasswordHasError = false;
    registerPasswordErrorText = '';
    update();
    return true;
  }

  // 验证确认密码
  bool _validateConfirmPassword(String password, String confirmPassword) {
    if (confirmPassword.isEmpty) {
      confirmPasswordHasError = true;
      confirmPasswordErrorText = 'Please confirm your password';
      update();
      return false;
    }

    if (password != confirmPassword) {
      confirmPasswordHasError = true;
      confirmPasswordErrorText = 'Passwords do not match';
      update();
      return false;
    }

    confirmPasswordHasError = false;
    confirmPasswordErrorText = '';
    update();
    return true;
  }

  // 邮箱密码登录
  Future<void> login() async {
    // 移除焦点并验证

    if (kDebugMode) {
      emailController.text = 'cx.930328@gmail.com';
      passwordController.text = 'cx123456';
      // emailController.text = 'chenxu.ios93@gmail.com';
      // passwordController.text = 'Cx123456';
    }
    unfocusAndValidate();

    String email = emailController.text.trim();
    String password = passwordController.text.trim();

    bool isEmailValid = _validateEmail(email);
    bool isPasswordValid = _validatePassword(password);

    if (!isEmailValid || !isPasswordValid) {
      return;
    }

    if (!agreementChecked) {
      LoadingUtils.showToast('请同意登录协议');
      return;
    }

    HttpResponse response = await HttpManager().post(
      API.userLogin,
      params: {'email': email, 'password': password},
      uiType: HttpUIType.loadingAndToast,
    );

    if (response.isSuccess) {
      AppUserManager().updateToken(response.data['token']).then((value) {
        if (value) {
          // 跳转到主页
          Get.offAndToNamed(AppRoutes.main);
        }
      });
    }
  }

  // 邮箱密码注册
  Future<void> register() async {
    if (kDebugMode) {
      registerEmailController.text = 'cx.930328@gmail.com';
      registerPasswordController.text = 'Cx123456';
      confirmPasswordController.text = 'Cx123456';
    }
    // 移除焦点并验证
    unfocusAndValidate();

    String email = registerEmailController.text.trim();
    String password = registerPasswordController.text.trim();
    String confirmPassword = confirmPasswordController.text.trim();

    bool isEmailValid = _validateRegisterEmail(email);
    bool isPasswordValid = _validateRegisterPassword(password);
    bool isConfirmPasswordValid =
        _validateConfirmPassword(password, confirmPassword);

    if (!isEmailValid || !isPasswordValid || !isConfirmPasswordValid) {
      return;
    }

    if (!registerAgreementChecked) {
      LoadingUtils.showToast('Please agree to the registration agreement');
      return;
    }

    // 跳转到验证码页面，传递邮箱和密码参数
    Get.toNamed(AppRoutes.emailVerification,
        arguments: {'email': email, 'password': password});
  }

  forgotPassword() {
    Get.toNamed(AppRoutes.forgetPassword);
  }
}
